<template>
  <div class="message-wrapper">
    <!-- 消息tab分类 -->
    <div class="tabWrapper">
        <div>
          <tab :line-width="2" class="tabItem" v-model="index">
            <tab-item :selected="selected === 1" @on-item-click="selected = 1">通知
              <badge v-if="noticeNum > 0" :text="noticeNum > 99 ? 99 : noticeNum"></badge>
            </tab-item>
          </tab>
        </div>
        <!-- 左右滚动swiper -->
        <div :style="{height: swiperHeight}">
            <!-- 通知消息swiper模块 -->
            <div v-if="selected === 1">
              <scroll v-if="noticeInfoList.length > 0" ref="noticeScroll" style="overflow: hidden; height: 100%"
                :style="{height: swiperHeight}"
                :data="noticeInfoList"
                :pullDownRefresh="true"
                :pullUpLoad="true"
                @pullingDown="onPullingDown"
                @pullingUp="onPullingUp">
                  <!-- 通知模块一 -->
                  <div>
                    <div class="noticeWrapper" v-for="item in noticeInfoList" :key="item.id">
                      <div class="noticeIcon">
                        <img slot="icon" :src="item.iconUrl !== undefined ? item.iconUrl : noticeImage" style="width:30px; height:30px;margin-right:8px;" v-if="item.messageType === 6">
                        <img slot="icon" :src="item.headUrl !== undefined ? item.headUrl : defaultAvatar" style="width:30px; height:30px;margin-right:8px;" v-else>
                      </div>
                      <div class="noticeDesc" @click="clickNoticeItem(item)">
                        <div class="noticeDescTitle">
                            <div class="noticeDescTitleLeft">
                              <p >{{item.messageContent.title}}</p>
                            </div>
                            <div class="iconStar">
                              <badge v-show="item.readStatus === 0 ? true : false"></badge>
                            </div>
                        </div>
                        <div class="noticeDescContext">
                            <p>{{item.messageContent.content}}</p>
                        </div>
                        <div class="noticeDescClick">
                            <p>点击立即查看>>></p>
                        </div>
                        <div class="noticeDescTime">
                          <p>{{item.publishTime}}</p>
                        </div>
                      </div>
                    </div>
                  </div>
              </scroll>
              <not-data v-else tip="空空如也~<br>点击刷新" @handleClick="getNotification(true)"></not-data>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import { localUser } from '@/assets/js/local'
import Scroll from '@/components/scroll/scroll'
import notData from '@/components/not-data/not-data'
import { Badge, Tab, TabItem, Swiper, SwiperItem } from 'vux'
import axios from '@/api/axiosApi'
import { QINIU_PREFIX } from '@/api/config'
import defaultAvatar from '@/assets/img/default_avatar.png'
import { mapGetters } from 'vuex'
import noticeImage from '@/assets/img/myhome/notice.png'
import { personifyTime } from '@/assets/js/utils'
import moment from 'moment'

export default {
  name: 'MessageList',
  data () {
    return {
      defaultAvatar: defaultAvatar,
      selected: 0,
      swiperHeight: 500 + 'px',
      index: 0,
      noticeImage: noticeImage,
      noticeInfoList: [],
      beforeNowTime: '',
      noticeNum: 0,
      conversationList: []
    }
  },
  components: {
    VHeader, Scroll, Badge, Tab, TabItem, Swiper, SwiperItem, moment, notData
  },
  created () {
    this.selected = 0
    this.pageNum = 1
    this.pageSize = 10
    this.user = localUser.get() || {}
    // 获取所有的通知消息
    this.getNotification(true)
    // 获取右边通知数量
    this.handleGetNoticeNum()
    // 会话列表
    let list = []
    this.syncConversation.forEach(item => {
      list.push({
        id: item.from_username,
        nickname: '',
        unreadMsgCount: item.unread_msg_count,
        lastedMsg: item.msgs[item.msgs.length - 1].content.msg_body.text,
        lastedMsgTime: personifyTime(item.msgs[item.msgs.length - 1].create_time),
        headUrl: ''
      })
      this._getAvatar(item.from_username)
    })
    this.conversationList = list
  },
  mounted () {
    this.swiperHeight = window.innerHeight - 60 - 44 + 'px'
  },
  computed: {
    ...mapGetters([
      'unreadChatCount', 'syncConversation', 'receiveMsg'
    ])
  },
  methods: {
    _getAvatar (id) {
      axios.get(this, `/v1/userInfo/${id}`, null, (data) => {
        if (data.headUrl) {
          if (data.headUrl.indexOf(QINIU_PREFIX) > -1) {
            data.headUrl += '-bheader'
          }
        } else {
          data.headUrl = defaultAvatar
        }
        this.conversationList.forEach(item => {
          if (item.id === data.id) {
            item.headUrl = data.headUrl
            item.nickname = data.nickname
          }
        })
      })
    },
    toChat (obj) {
      this.$store.dispatch('setChatObject', obj)
      this.$router.push('/chat')
    },
    getNotification (isFirst) {
      axios.get(this, '/v1/notification/' + this.user.id, {pageNum: this.pageNum, pageSize: this.pageSize}, (data) => {
        data.forEach(item => {
          item.publishTime = this.moment(item.createAt).from(this.moment())
          item.messageContent = JSON.parse(item.messageContent)
        })
        if (isFirst) {
          this.noticeInfoList = data
          return
        }
        if (data.length === 0) {
          if (this.pageNum === 1) {
            this.$refs.noticeScroll.hiddenPullDown()
          } else {
            this.pageNum--
            this.$refs.noticeScroll.hiddenPullUpLoad()
          }
        } else {
          if (this.pageNum > 1) {
            this.noticeInfoList = this.noticeInfoList.concat(data)
          } else {
            this.noticeInfoList = data
          }
        }
      })
    },
    changeReadStatus (id, readStatus) {
      if (readStatus === 1) {
        return
      }
      // 修改本地未读状态
      for (let i = 0; i < this.noticeInfoList.length; i++) {
        const item = this.noticeInfoList[i]
        if (item.id === id) {
          item.readStatus = 1
          break
        }
      }
      axios.put(this, '/v1/notification/readStatus', {id: id})
    },
    onPullingUp () {
      this.pageNum++
      this.getNotification()
    },
    onPullingDown () {
      this.pageNum = 1
      this.getNotification()
    },
    clickNoticeItem(item) {
      this.changeReadStatus(item.id, item.readStatus)
      this.noticeNum--
      setTimeout(() => {
        switch (item.messageType) {
          case 1:
            this.$router.push('/user/archives/' + item.messageContent.follower)
            break
          case 201:
          case 301:
          case 401:
            this.$router.push('/meiTu/dynamicDesc/' + item.messageContent.dynamicId)
            break
          case 202:
          case 203:
          case 302:
          case 303:
          case 402:
          case 403:
            this.$router.push('/address/playStrategy/' + item.messageContent.playStrategyId)
            break
          case 501:
            this.$router.push('/meiTu/dynamicDesc/' + item.messageContent.targetId)
            break
          case 502:
          case 503:
            this.$router.push('/address/playStrategy/' + item.messageContent.targetId)
            break
          case 504:
            this.$router.push('/cart/product/' + item.messageContent.targetId + '/0')
            break
          case 505:
            this.$router.push('/cart/product/' + item.messageContent.targetId + '/1')
            break
          default:
            this.$vux.toast.text('没找到对应的页面', 'middle')
        }
      }, 200)
    },
    setHaveReaded () {
      this.noticeNum = 0
      axios.put(this, '/v1/notification/readStatus', {userId: this.user.id}, (data) => {
        // 修改本地未读状态
        for (let i = 0; i < this.noticeInfoList.length; i++) {
          const item = this.noticeInfoList[i]
          item.readStatus = 1
        }
      })
    },
    // 获取未读的通知数量
    handleGetNoticeNum () {
      axios.get(this, '/v1/notification/notReadCount/' + this.user.id, null, (data) => {
        this.noticeNum = data
      })
    }
  },
  watch: {
    receiveMsg () {
      this.receiveMsg.messages.forEach(item => {
        const index = this.conversationList.findIndex(o => o.id === item.from_username)
        if (index > -1) {
          this.conversationList[index].lastedMsg = item.content.msg_body.text
          this.conversationList[index].lastedMsgTime = personifyTime(item.content.msg_body.create_time)
          this.conversationList[index].unreadMsgCount += 1
        } else {
          this.conversationList.push({
            id: item.from_username,
            nickname: '',
            headUrl: '',
            lastedMsg: item.content.msg_body.text,
            lastedMsgTime: personifyTime(item.content.msg_body.create_time),
            unreadMsgCount: 1
          })
          this._getAvatar(item.from_username)
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
.message-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $color-background;
  z-index: 101;

  .message-list {
    list-style: none;

    li {
    }
    .message {
      padding: 7px 9px;
      background: #ffffff;
      position: relative;
      display: flex;
      border-bottom: 0.5px solid $color-border;

      .avator {
        width: 50px;
        height: 50px;
        min-width 50px;
        border-radius: 50%;
      }

      .content {
        width: calc(100% - 145px)
        padding: 0 9px;
        line-height: 1.6;
        p {
          color: $color-text-dark;
          white-space: nowrap;
          overflow: hidden;
          text-overflow:ellipsis;
        }
      }

      .right {
        width: 120px;
        text-align: right;
        .time {
          color: $color-text-dark;
          font-size: 14px;
        }
      }
    }
  }
}


.noticeWrapper {
  display flex
  padding-left 15px
  padding-right 15px
  padding-top 15px
  padding-bottom 12px
  border-bottom-style solid
  border-width:1px
  border-color: #E4E4E4
  background-color white
  .noticeIcon {
    width 38px
    justify-content space-between
    .iconImage {

    }
    .iconStar {

    }
  }
  .noticeDesc {
    width calc(100%)
    margin-left 5px
    .noticeDescTitle {
      display flex
      justify-content space-between
      .noticeDescTitleLeft {
        p {
          font-weight bold
        }
      }
      .iconStar {

      }
    }
    .noticeDescContext {
    }
    .noticeDescClick {
      p {
        font-size $font-size-desc
      }
    }
    .noticeDescTime {
      margin-top 5px
      p {
        font-size $font-size-small
      }
    }
  }
}
</style>
